//
//  QCOAuthViewController.swift
//  SwiftDemoWithSina
//
//  Created by qu on 2017/1/18.
//  Copyright © 2017年 Apple. All rights reserved.
//

import UIKit
import YYModel
import SVProgressHUD


class QCOAuthViewController: UIViewController {

    
    override func loadView() {
        
        view = webView
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(APPKEY)&redirect_uri=\(REDIRECT_URI)"
        
        let url = URL(string: urlString)
        
        guard let u = url  else {
            return
        }
        
        let request = URLRequest(url: u)
        webView.loadRequest(request)
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
    }

    private func setupUI() {
     view.backgroundColor = UIColor.white
        setupNav()
    }
    
    private func setupNav() {
    title = "微博登录"
        navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: nil, title: "取消", target: self, action: #selector(cancelClick))
        navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: nil, title: "自动填充", target: self, action: #selector(autofillClick))
    }
    
    //懒加载
   fileprivate lazy var webView: UIWebView = {
    let view = UIWebView()
       view.delegate = self
        return view
    
    }()

}

extension QCOAuthViewController: UIWebViewDelegate {
    
    //开始加载
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    //加载完成
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //将要加载请求的字符串
        let urlString = request.url?.absoluteString
       //判断URLString 是否为nil 且字符串的前缀是回调页 前缀 hasPrefix
        if let u = urlString,u.hasPrefix(REDIRECT_URI) {
            //请求参数部分
            let query = request.url?.query
            //判断query 是否为nil 
            if let q = query {
                
                print(q)
              //截取code
              let code = q.substring(from: "code=".endIndex)
               //拿到code 发送请求获取accessToken
              QCOAuthViewModel.shared.getUserAccount(code: code, isFinish: { (isFinish) in
                if !isFinish {
                    return
                } else {
                    self.dismiss(animated: false, completion: { 
                        NotificationCenter.default.post(name:NSNotification.Name (rawValue:SWITCHROOTVIEWCONTROLLERNOTI),object:nil)
                    })
                }
              })
              return false
            }
        }
       return true
    }
}

extension QCOAuthViewController {
    
    @objc fileprivate func cancelClick() {
        dismiss(animated: true, completion: nil)

    }
    @objc fileprivate func autofillClick() {
        print("自动填充点击")
        // js
        let jsString = "document.getElementById('userId').value='\(HMWBNAME)';document.getElementById('passwd').value='\(HMWBPASSWD)';"
        // js注入
        webView.stringByEvaluatingJavaScript(from: jsString)
    }
    
}
